<template>
  <div>
    <BasicModal
      @register="register"
      :title="title"
      width="600px"
      :destroyOnClose="true"
      :canFullscreen="false"
      :showOkBtn="false"
      :showCancelBtn="false"
    >
      <BasicForm @register="registerForm">
        <template #num>
          <span>{{ checkedRows.length }}个</span>
          <Button type="link" size="small" @click="handleOpenInstitution">查看</Button>
        </template>
      </BasicForm>
    </BasicModal>
    <InstitutionModal @register="registerInstitution" />
    <PublishError @register="registerPublishError" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { Button } from '@/components/Button';
  import InstitutionModal from './institutionModal.vue';
  import PublishError from '../../components/publishError.vue';
  import { useModal } from '@/components/Modal';
  import { ref } from 'vue';
  import { historyVersion, revertCodeRelease } from '@/api/version';
  import { useMessage } from '@/hooks/web/useMessage';
  import { IVersionPageListResult } from '@/api/version/type';

  const title = ref('发布体验版');
  const type = ref(1);
  const tenantIds = ref<number[]>([]);
  // const userVersion = ref();
  const checkedRows = ref<IVersionPageListResult[]>([]);
  const { createMessage } = useMessage();

  const emit = defineEmits(['reload']);

  const baseSchemas: FormSchema[] = [
    { field: 'userDesc', component: 'InputTextArea', label: '提交说明' },
  ];

  const [registerForm, { validate, appendSchemaByField, setProps }] = useForm({
    schemas: [],
    autoFocusFirstItem: true,
    actionColOptions: {
      span: 24,
    },
    labelWidth: 120,
    baseColProps: { span: 18 },
    submitButtonOptions: {
      text: '确认',
    },
    resetButtonOptions: {
      text: '取消',
    },
    submitFunc: async () => {
      const data = await validate();
      console.log(data);
      setProps({
        submitButtonOptions: {
          loading: true,
        },
      });
      try {
        let res = await revertCodeRelease({
          tenantIds: tenantIds.value,
          userDesc: data.userDesc,
          userVersion: data.userVersion,
        });
        setProps({
          submitButtonOptions: {
            loading: false,
          },
        });
        if (res && res.length) {
          return openPublishErrorModal(true, {
            list: res,
          });
        }
        createMessage.success('提交成功！');
        emit('reload');
        closeModal();
      } catch (error) {
        setProps({
          submitButtonOptions: {
            loading: false,
          },
        });
      }
    },
    resetFunc: async () => {
      closeModal();
    },
  });

  const [register, { closeModal }] = useModalInner((data) => {
    console.log('data--->', data);
    type.value = data.type;
    let row = data.row;
    title.value = (data.type === 2 ? '批量' : '') + '版本回滚';

    let schemas: FormSchema[] = [];
    if (data.type === 1) {
      tenantIds.value = [row.tenantId] as any;
      schemas = [
        {
          field: 'organizationName',
          component: 'Input',
          label: '机构名称',
          componentProps: { disabled: true },
          defaultValue: row.organizationName,
        },
        {
          field: 'wechatAppName',
          component: 'Input',
          label: '小程序名称',
          componentProps: { disabled: true },
          defaultValue: row.wechatAppName,
        },
        {
          field: 'releaseVersion',
          component: 'Input',
          label: '当前版本',
          componentProps: { disabled: true },
          defaultValue: row.releaseVersion,
        },
        {
          field: 'userVersion',
          component: 'ApiSelect',
          label: '回滚版本',
          componentProps: {
            api: historyVersion,
            params: { tenantId: row.tenantId },
            immediate: false,
            labelField: 'user_version',
            valueField: 'user_version',
            onChange: (e, v) => {
              console.log('selected:', e, v);
              // userVersion.value = v.label;
            },
          },
        },
        ...baseSchemas,
      ];
    } else if (data.type === 2) {
      checkedRows.value = row;
      tenantIds.value = checkedRows.value.map((v) => v.tenantId);
      schemas = [
        { field: 'type', component: 'Input', label: '机构数量', slot: 'num' },
        {
          field: 'type',
          component: 'Input',
          label: '回滚版本',
          componentProps: { disabled: true },
          defaultValue: '上一个版本',
        },
        ...baseSchemas,
      ];
    }

    schemas.forEach((item) => {
      appendSchemaByField(
        {
          ...item,
        },
        '',
      );
    });
  });

  const [registerInstitution, { openModal }] = useModal();
  const [registerPublishError, { openModal: openPublishErrorModal }] = useModal();

  function handleOpenInstitution() {
    openModal(true, {
      list: checkedRows.value.map((v) => v.organizationName),
    });
  }
</script>

<style lang="less" scoped></style>
